﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
using System.ComponentModel;

namespace H2.NET
{
    public class ImageHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }
        /// <summary>
        /// The ProcessRequest Method is used to write the image to the response
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string cacheKey = context.Request["ImageContent"];

                if (String.IsNullOrEmpty(cacheKey))
                {
                    return;
                }

                bool enableCaching = false;
                if (!String.IsNullOrEmpty(context.Request["EnableCaching"]))
                {
                    Boolean.TryParse(context.Request["EnableCaching"], out enableCaching);
                }

                string mimeType = context.Request["MimeType"];
                if (string.IsNullOrEmpty(mimeType))
                {
                    mimeType = "image/jpeg";
                }

                byte[] imageData = context.Cache[cacheKey] as byte[];

                if (!enableCaching)
                {
                    context.Cache.Remove(cacheKey);
                }

                context.Response.ContentType = mimeType;

                if (imageData != null)
                {
                    context.Response.OutputStream.Write(imageData, 0, imageData.Length);
                }

            }
            catch (Exception)
            { 
            
            }
        }

        #endregion
    }        
}